/*
 * Copyright 2011-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0.
 * See `LICENSE` in the project root for license information.
 */

package me.ijleex.mgmt.framework.test.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * ZooKeeperDemo
 *
 * @author liym
 * @since 2019-04-16 16:34 新建
 */
public class ZooKeeperDemo implements Watcher {

    private static CountDownLatch connectedLatch = new CountDownLatch(1);

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Receive watched event: " + event);
        if (Event.KeeperState.SyncConnected == event.getState()) {
            connectedLatch.countDown();
        }
    }

    public static void main(String[] args) throws IOException {
        String connectString = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183";
        ZooKeeper zookeeper = new ZooKeeper(connectString, 5000, new ZooKeeperDemo());
        System.out.println("State1: " + zookeeper.getState());
        try {
            connectedLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Zookeeper session established");
        System.out.println(zookeeper);
        System.out.println("State2: " + zookeeper.getState());

        try {
            zookeeper.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("State3: " + zookeeper.getState());
    }

}
